var basePath = $("#basePath").val();
$(document).ready(function (){
    menuCss("维修商");
    var url = basePath + "/base/queryProvince";
    publicAjax(url,"POST",{},function (data) {
        if(data.ret == 200){
            initQueryMainData(data.data);
        }else {
            flavrShowByTime(data.msg,null,"danger",false);
            return;
        }
    });

    $("#queryForm").find("[name='cityId']").val(null);
    $("#queryForm").find("[name='cityId']").select2({
        language: 'zh-CN',
        placeholder: '请选择城市',
        allowClear: true});
    $("#queryForm").find("[name='areaId']").val(null);
    $("#queryForm").find("[name='areaId']").select2({
        language: 'zh-CN',
        placeholder: '请选择区域',
        allowClear: true});

    queryMainList(0,10);
    $("#show-count").change(function(){
        queryMainList(0,$("#show-count").val());
    })
    bindEvent();

    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
});


function initQueryMainData(object){
    var province = $("#queryForm").find("[name='provinceId']");
    $(province).html("");
    var html = "";
    $.each(object,function (index,item) {
        html += "<option value='"+item.provinceId+"'>"+item.province+"</option>"
    });
    $(province).html(html);
    $(province).val(null);
    $(province).select2({language: 'zh-CN',placeholder: "请选择省份",allowClear: true});
}



function bindEvent() {
    $("#search").click(function (){
        queryMainList(0,10)
    });

    $("#add").click(function (){
        initAddMainData();
        $("#add-modal").iziModal("open",this);
    });

    $("#saveMain").click(function (){
        saveMain();
    });

    $("#edit").click(function (){
        initAddMainData();
        editMainInitData();
    });

    $("#import").click(function (){
        location.href=basePath+"/maintainer/import";
    });

    $("#queryForm").find("[name='provinceId']").change(function (){
        var value = $(this).val();
        if(value == null || value == ""){
            $("#queryForm").find("[name='cityId']").html("");
            $("#queryForm").find("[name='areaId']").html("");
            return;
        }
        var url = basePath + "/base/queryCity";
        publicAjax(url,"POST",{"provinceId":value},function (data) {
            var city = $("#queryForm").find("[name='cityId']");
            $(city).html("");
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.cityId+"'>"+item.city+"</option>"
            });
            $(city).html(html);
            $(city).val(null);
            $(city).select2({language: 'zh-CN',placeholder: "请选择城市",allowClear: true});
        })
    });

    $("#queryForm").find("[name='cityId']").change(function (){
        var value = $(this).val();
        if(value == null || value == ""){
            $("#queryForm").find("[name='areaId']").html("");
            return;
        }
        var url = basePath + "/base/queryArea";
        publicAjax(url,"POST",{"cityId":value},function (data) {
            var area = $("#queryForm").find("[name='areaId']");
            $(area).html("");
            var html = "";
            $.each(data.data,function (index,item) {
                html += "<option value='"+item.areaId+"'>"+item.area+"</option>"
            });
            $(area).html(html);
            $(area).val(null);
            $(area).select2({language: 'zh-CN',placeholder: "请选择区域",allowClear: true});
        })

    });
}

function queryMainList(start,limit){
    var json = {};
    json.start = start;
    json.end = $("#show-count").val();
    var maintainerName = $("#queryForm").find("[name='maintainerName']").val();
    var provinceId = $("#queryForm").find("[name='provinceId']").val();
    var cityId = $("#queryForm").find("[name='cityId']").val();
    var areaId = $("#queryForm").find("[name='areaId']").val();
    json.maintainerName = maintainerName;
    json.provinceId = provinceId;
    json.cityId = cityId;
    json.areaId = areaId;
    var url = basePath + "/maintainer/queryMaintainerList";
    publicAjax(url,"POST",json,function (data) {
        if(data.ret == 200){
            bindMainList(data.data.list);
            $("#total-count").text(data.data.count);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function bindMainList(obj){
    $("#main_table").html("");
    var html = "";
    if(obj == null || obj.length == 0){
        html="<tr><td class='text-center' colspan='12'>暂无数据</td></tr>";
    }

    $.each(obj,function (index,item) {
        var manufacturerName = '';
        if(item.manufacturerName != null && item.manufacturerName  != ''){
            manufacturerName = item.manufacturerName+"..."
        }
        html+="<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
            "<td class='text-center text-muted'><input type='checkbox' class='flat-green' name='one' value='"+item.maintainerId+"'></td>" +
            "<td class='text-muted'>"+(item.maintainerNo==null?'':item.maintainerNo)+"</td>" +
            "<td class='text-muted'>"+(item.maintainerName==null?'':item.maintainerName)+"</td>" +
            "<td class='text-muted'>"+(item.shortName==null?'':item.shortName)+"</td>" +
            "<td class='text-muted'>"+(item.creditCode==null?'':item.creditCode)+"</td>" +
            "<td class='text-muted'>"+(item.registrationNumber==null?'':item.registrationNumber)+"</td>" +
            "<td class='text-muted'>"+(item.region==null?'':item.region)+"</td>" +
            "<td class='text-muted'><a href='javascript:showManufacturer("+item.maintainerId+")'>" + (manufacturerName)+ "</a></td>" +
            "<td class='text-muted'>"+(item.maintainerContacts==null?'':item.maintainerContacts)+"</td>" +
            "<td class='text-muted'>"+(item.maintainerPhone==null?'':item.maintainerPhone)+"</td>" +
            "<td class='text-muted'>"+(item.address==null?'':item.address)+"</td>" +
            "</tr>"
    });
    $("#main_table").html(html);
    initDomCss();
}

function showManufacturer(id){
    var url = basePath+"/manufacturer/queryManufacturerListBymainId";
    publicAjax(url,"POST",{maintainerId:id},function (data){
        if(data.ret == 200){
            bindManufacturerListData(data.data);
        }else{
            flavrShowByTime(data.msg,null,"danger",false);
        }
    });
}

function bindManufacturerListData(obj){

    $("#manufacturer_list").html("");
    if(obj == null || obj.length == 0){
        $("#manufacturer_list").html("<tr><td colspan='8' class='text-muted text-center'>暂无厂商信息</td></tr>");
    }else{
        var html = "";
        $.each(obj,function (index,item) {
            html+="<tr><td class='text-center text-muted'>"+(index+1)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerNo==null?'':item.manufacturerNo)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerName==null?'':item.manufacturerName)+"</td>" +
                "<td class='text-center text-muted'>"+(item.shortName==null?'':item.shortName)+"</td>" +
                "<td class='text-center text-muted'>"+(item.region==null?'':item.region)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerContacts==null?'':item.manufacturerContacts)+"</td>" +
                "<td class='text-center text-muted'>"+(item.manufacturerPhone==null?'':item.manufacturerPhone)+"</td>" +
                "</tr>"
        });
        $("#manufacturer_list").html(html);
    }
    $("#manufacturer_modal").iziModal("open",this);
}


function initDomCss(){
    $('input[type="checkbox"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    $("input[name='one']").on('ifChecked', function(event){
        var current = $(this).parents("tr").index();
        $("[name='one']:checked").each(function(i){
            if($(this).parents("tr").index()!=current){
                $(this).iCheck('uncheck');
            }
        });
    });
}

$("#manufacturer_modal").iziModal({
    title: "厂商信息",
    headerColor: '#00c0ef',
    rtl: false,
    width: 1000,
    zindex: 1042,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    onOpening: function () {
    },
    onOpened: function () {
    },
    onClosing: function () {
    },
    onClosed: function () {

    }
});


$("#add-modal").iziModal({
    title: "编辑维修商",
    headerColor: '#00c0ef',
    rtl: false,
    width: 800,
    zindex: 1042,
    group: '',
    loop: false,
    history: false,
    restoreDefaultContent: false,
    autoOpen: false, // Boolean, Number
    bodyOverflow: false,
    fullscreen: true,
    openFullscreen: false,
    closeOnEscape: false,
    onOpening: function () {
        //initAddHospitalData();
        validator();
    },
    onOpened: function () {
    },
    onClosing: function () {
    },
    onClosed: function () {
        $("#add-update-from").find("[name='maintainer']").val(null);
        $('#add-update-from')[0].reset();
        $("#add-update-from").find("[name='cityId']").html("");
        $("#add-update-from").find("[name='areaId']").html("");
        $("#add-update-from").data('bootstrapValidator').destroy();

    }
});


function validator(){
    $('#add-update-from').bootstrapValidator({
        excluded: [':disabled', ':hidden', ':not(:visible)'],
        live: 'enabled',
        message: '非有效值',
        fields: {
            maintainerName: {
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            },maintainerNo:{
                validators: {
                    notEmpty: {
                        message: '不能为空'
                    }
                }
            }
        }
    });
}


function initAddMainData(){
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });

    var province = $("#add-update-from").find("[name='provinceId']");
    var city = $("#add-update-from").find("[name='cityId']");
    var area = $("#add-update-from").find("[name='areaId']");

    $(province).html($("#queryForm").find("[name='provinceId']").html());
    $(province).val(null);

    $("#add-update-from").find("[name='provinceId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
    $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
    $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});


    $(province).change(function (){
        provinceChang(null,function (){
            $("#add-update-from").find("[name='cityId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        });
    });

    $(city).change(function (){
        cityChang(null,function (){
            $("#add-update-from").find("[name='areaId']").select2({language: 'zh-CN',placeholder: "请选择",allowClear: true});
        });
    });
}



function provinceChang(cityId,fn){
    var value = $("#add-update-from").find("[name='provinceId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='cityId']").html("");
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryCity";
    publicAjax(url,"POST",{"provinceId":value},function (data) {
        $("#add-update-from").find("[name='cityId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.cityId == cityId){
                html += "<option value='"+item.cityId+"' selected>"+item.city+"</option>"
            }else{
                html += "<option value='"+item.cityId+"'>"+item.city+"</option>"
            }

        });
        $("#add-update-from").find("[name='cityId']").html(html);
        $("#add-update-from").find("[name='cityId']").val(null);
        fn();
    })

}

function cityChang(areaId,fn){
    var value = $("#add-update-from").find("[name='cityId']").val();
    if(value == null || value == ""){
        $("#add-update-from").find("[name='areaId']").html("");
        return;
    }
    var url = basePath + "/base/queryArea";
    publicAjax(url,"POST",{"cityId":value},function (data) {
        $("#add-update-from").find("[name='areaId']").html("");
        var html = "";
        $.each(data.data,function (index,item) {
            if(item.areaId == areaId){
                html += "<option value='"+item.areaId+"' selected>"+item.area+"</option>"
            }else{
                html += "<option value='"+item.areaId+"'>"+item.area+"</option>"
            }
        });
        $("#add-update-from").find("[name='areaId']").html(html);
        $("#add-update-from").find("[name='areaId']").val(null);
        fn();
    })
}

var bl = false;
function saveMain(){
    $('#add-update-from').bootstrapValidator('validate');
    if($('#add-update-from').data('bootstrapValidator').isValid()){
        if(!bl){
            bl = true;
            var url = basePath+"/maintainer/addOrUpdateMaintainer"
            publicAjax(url,"POST",$("#add-update-from"),function (data) {
                if(data.ret == 200){
                    flavrShowByTime(data.msg,null,"success",false);
                    queryMainList(0,10);
                    $("#add-modal").iziModal("close", this);
                    bl=false;
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                    bl=false;
                }
            })
        }
    }
}



function editMainInitData(){
    if(!$("input[name='one']:checked").length){
        flavrShowByTime("请选择一个维修商", null, "danger", false);
        return;
    }
    var json = {"maintainerId":$("input[name='one']:checked").val()};
    var url=basePath+"/maintainer/queryMaintainerInfo";
    publicAjax(url,"POST",json,function (data) {
        bindManuInfo(data.data);
    });
}
function bindManuInfo(obj){
    $("#add-update-from").find("[name='maintainerId']").val(obj.maintainerId );
    $("#add-update-from").find("[name='maintainerName']").val(obj.maintainerName== null ? '': obj.maintainerName);
    $("#add-update-from").find("[name='creditCode']").val(obj.creditCode== null ? '': obj.creditCode);
    $("#add-update-from").find("[name='registrationNumber']").val(obj.registrationNumber== null ? '': obj.registrationNumber);
    $("#add-update-from").find("[name='address']").val(obj.address== null ? '': obj.address);
    $("#add-update-from").find("[name='manufacturerContacts']").val(obj.manufacturerContacts== null ? '': obj.manufacturerContacts);
    $("#add-update-from").find("[name='manufacturerPhone']").val(obj.manufacturerPhone== null ? '': obj.manufacturerPhone);
    $("#add-update-from").find("[name='remark']").val(obj.remark== null ? '': obj.remark);
    $("#add-update-from").find("[name='maintainerNo']").val(obj.maintainerNo== null ? '': obj.maintainerNo);
    $("#add-update-from").find("[name='shortName']").val(obj.shortName==null ? '': obj.shortName);

    if(obj.provinceId != null){
        $("#add-update-from").find("[name='provinceId']").val(obj.provinceId);
        showText($("#add-update-from").find("[name='provinceId']"));
    }


    provinceChang(obj.cityId,function (){
        $("#add-update-from").find("[name='cityId']").val(obj.cityId);
        showText( $("#add-update-from").find("[name='cityId']"));

        cityChang(obj.areaId,function (){
            $("#add-update-from").find("[name='areaId']").val(obj.areaId).change();
            showText( $("#add-update-from").find("[name='areaId']"));
        });
    });

    $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").attr("checked",true);
    $("input[type='radio'][name='isDel'][value='"+obj.isDel+"']").addClass("checked");
    $('input[type="radio"].flat-green').iCheck({
        checkboxClass: 'icheckbox_flat-green',
        radioClass: 'iradio_flat-green'
    });
    $("#add-modal").iziModal("open",this);
}

function showText(obj){
    var text2 =$(obj).find("option:selected").text();
    $(obj).select2({language:'zh-CN', placeholder:text2, allowClear:true});
}

//分页
function Pagination(total,limit,current){
    $('.M-box3').empty();
    $('.M-box3').pagination({
        totalData:total,
        showData:limit,//数据总数totalData和每页显示的条数showData必须同时配置，否则默认使用总页数pageCount;limit可选值 5 10 20 50
        //pageCount:50,
        current:current,
        jump:true,
        coping:true,
        homePage:'首页',
        endPage:'末页',
        prevContent:'上页',
        nextContent:'下页',
        callback:function(index){
          start = (index.getCurrent()-1)*limit;
          limit = index.getShowData();
          queryMainList(start,limit);
        }
  });
}

